package com.panda.utils;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class FileUtil {
	public static boolean encrypt(String path, String password) throws Exception {
		RandomAccessFile raf = new RandomAccessFile(new File(path), "rw");
		int pwl = password.getBytes().length;
		if (!isencrypt(raf, password)) {
			int reaLen = 0;
			long seek = 0L;
			byte[] datas = new byte[102400];
			while ((reaLen = raf.read(datas)) != -1) {
				raf.read(datas, 0, datas.length);
				encrypt(datas, password);
				raf.seek(seek);
				raf.write(datas, 0, reaLen);
				seek += reaLen;
			}
			raf.write(password.getBytes(), 0, pwl);
		}
		raf.close();
		return true;
	}

	public static boolean uncrypt(String path, String password) throws Exception {
		RandomAccessFile raf = new RandomAccessFile(new File(path), "rw");
		int pwl = password.getBytes().length;
		if (isencrypt(raf, password)) {
			int reaLen = 0;
			long seek = 0L;
			byte[] datas = new byte[102400];
			while ((reaLen = raf.read(datas)) != -1) {
				raf.read(datas, 0, datas.length);
				uncrypt(datas, password);
				raf.seek(seek);
				raf.write(datas, 0, reaLen);
				seek += reaLen;
			}
			raf.setLength(raf.length() - pwl);
			raf.close();
		}
		return true;
	}

	public static byte[] encrypt(byte[] source, String password) throws Exception {
		byte[] miya = password.getBytes();
		int mlenth = miya.length;
		for (int i = 0; i < source.length; i++) {
			source[i] = (byte) (source[i] + miya[i % mlenth]);
		}
		return source;
	}

	public static byte[] uncrypt(byte[] source, String password) throws Exception {
		byte[] miya = password.getBytes();
		int mlenth = miya.length;
		for (int i = 0; i < source.length; i++) {
			source[i] = (byte) (source[i] - miya[i % mlenth]);
		}
		return source;
	}

	public static boolean isencrypt(RandomAccessFile raf, String password) throws IOException {
		int pwl = password.getBytes().length;
		if (raf.length() < pwl) {
			return false;
		}
		raf.seek(raf.length() - pwl);
		byte[] datas = new byte[102400];
		raf.read(datas, 0, pwl);
		raf.seek(0);
		String paw = new String(datas, 0, pwl);
		if (paw.equals(password)) {
			return true;
		} else {
			return false;
		}
	}
}
